﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.EventSystems;
using DG.Tweening;

public class DishController : EventBehaviour {
    public static bool IsDraging {
        get; private set;
    }

    static Camera _camera;

    public float height = 0.5f;

    Transform _transform;
    Rigidbody _rigidbody;
    Collider _collider;
    bool _isDraging;
    Vector3 _size;
    ForceController _forceController;

	void Start() {
        _transform = GetComponent<Transform>();
        _rigidbody = GetComponent<Rigidbody>();
        _collider = GetComponent<Collider>();
        _size = GetComponent<MeshFilter>().mesh.bounds.size * _transform.localScale.x;

        if (_camera == null) {
            _camera = _transform.root.GetComponentInChildren<Camera>();
        }
    }

    public override void OnPointerClick(PointerEventData eventData) {
        if (_isDraging) {
            return;
        }

        var endValue = new Vector3(_transform.localEulerAngles.x * -1f, 0f);

        if (Mathf.Abs(endValue.x) < 45f) {
            endValue = _transform.right * 90f;
        }

        _transform.DOLocalMoveY(height, 0.5f);
        _rigidbody.DORotate(endValue, 0.5f);
    }

    public override void OnBeginDrag(PointerEventData eventData) {
        _isDraging = true;
        ChineseRestaurantManager.Instance.EnableFloater(false);
        ForceController.isDraging = true; 
    }

    public override void OnDrag(PointerEventData eventData) {
        Ray ray = _camera.ScreenPointToRay(Input.mousePosition);
        RaycastHit hitInfo;

        if (Physics.Raycast(ray, out hitInfo)) {
            if (_forceController == null) {
                _forceController = FindObjectOfType<ForceController>();
            }

            _forceController.enabled = false;

            var power = (ChineseRestaurantManager.Instance.currentDishName == DishName.QingCaiDouFuTang) ? 6f : 4f;

            if (!Application.isEditor) {
                power *= 3f;
            }

            PhysicsUtility.ApplyExplosionForce(hitInfo.point, 0.5f, power, 0f);
            IsDraging = true;
            ShowHideTips();
        }
    }

    public override void OnEndDrag(PointerEventData eventData) {
        _isDraging = false;
        ChineseRestaurantManager.Instance.EnableFloater(SwitchController.IsOn ? false : true);
        ForceController.isDraging = false;

        if (_forceController == null) {
            _forceController = FindObjectOfType<ForceController>();
        }

        _forceController.enabled = true;
        IsDraging = false;
    }

    void ShowHideTips() {
        if (ChineseRestaurantManager.Instance.currentDishName == DishName.QingCaiDouFuTang) {
            FindObjectOfType<StockpotController>().ShowHideTips();
        } else {
            FindObjectOfType<PanController>().ShowHideTips();
        }
    }
}
